package com.smartum.mpr.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.smartum.mpr.exception.DatabaseIntegrityException;
import com.smartum.mpr.exception.NotCorrectPermission;
import com.smartum.mpr.model.ItemPurchase;
import com.smartum.mpr.model.JobPurchase;

@Repository
public class JobPurchaseDao extends BaseDao<JobPurchase>{


	public JobPurchase getJobPurchase(long categoryId, long userId) throws DatabaseIntegrityException, NotCorrectPermission{
		DetachedCriteria criteria = DetachedCriteria.forClass(JobPurchase.class);
		criteria.createCriteria("user").add(Restrictions.eq("id", userId));
		criteria.createCriteria("category").add(Restrictions.eq("id", categoryId));

		List<JobPurchase> purchases = hibernateTemplate.findByCriteria(criteria);
		if (purchases.size() == 0) {
			throw new NotCorrectPermission("no_permission_to_post_job");
		} else if (purchases.size() > 1) {
			throw new DatabaseIntegrityException("database has few equals purchasess");
		} else if (purchases.size() == 1) {
			return purchases.get(0);
		} else {
			throw new DatabaseIntegrityException();
		}
	}

	@Override
    protected Class<JobPurchase> getEntityClass() {
	    return JobPurchase.class;
    }
	
	public void deletePurchase(JobPurchase entity){
		hibernateTemplate.delete(entity);
	}
	

}
